The Scripting app allows you to write quantity-based health data (such as step count, heart rate, calories, and more) to Apple HealthKit using the HealthQuantitySample
class and the Health.saveQuantitySample
method.
This guide explains how to create and save a new quantity sample.
Ensure HealthKit is available on the device:
Make sure your script has the appropriate write permission for the quantity type you want to save. Permissions are requested automatically when you call save APIs.
HealthQuantitySample
Use HealthQuantitySample.create()
to instantiate a new sample.
type
: A HealthQuantityType
string, such as "stepCount"
, "heartRate"
, "bodyMass"
, etc.startDate
: The start of the measurement period (a JavaScript Date
object).endDate
: The end of the measurement period (a JavaScript Date
object).value
: The numeric value of the sample.unit
: A HealthUnit
representing the measurement unit (e.g., HealthUnit.count()
, HealthUnit.gram()
, HealthUnit.meter()
).metadata
(optional): An object containing additional metadata.After creating the sample, use Health.saveQuantitySample()
to store it in the HealthKit database.
If saving fails (e.g., due to missing permissions), the promise will reject with an error.
The unit must match the type. For example:
"stepCount"
→ HealthUnit.count()
"bodyMass"
→ HealthUnit.gram(HealthMetrixPrefix.kilo)
"heartRate"
→ HealthUnit.count().divided(HealthUnit.minute())
If the sample’s type is cumulative (e.g., steps, distance), the startDate
and endDate
should cover the time window over which the value was measured.